/* Copyright (c) 2009 - 2010 98Labs Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sbal89.map.server;

import static com.sbal89.map.util.BaseUtil.COLON;
import static com.sbal89.map.util.BaseUtil.CREATEMAP_VIEW;
import static com.sbal89.map.util.BaseUtil.DEFAULT_VIEW;
import static com.sbal89.map.util.BaseUtil.DOT;
import static com.sbal89.map.util.BaseUtil.EMBEDCODE_VIEW;
import static com.sbal89.map.util.BaseUtil.MESSAGE;
import static com.sbal89.map.util.BaseUtil.P_KEY;
import static com.sbal89.map.util.BaseUtil.P_RESID;
import static com.sbal89.map.util.BaseUtil.P_TITLE;
import static com.sbal89.map.util.BaseUtil.P_TYPE;
import static com.sbal89.map.util.BaseUtil.R_KEY;
import static com.sbal89.map.util.BaseUtil.R_TYPE;
import static com.sbal89.map.util.BaseUtil.SHEET_VIEW;
import static com.sbal89.map.util.BaseUtil.USER;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gdata.data.docs.DocumentListEntry;
import com.google.gdata.util.ServiceException;
import com.sbal89.map.model.Document;
import com.sbal89.map.model.Msg;
import com.sbal89.map.model.User;
import com.sbal89.map.util.DLDAUtil;

@SuppressWarnings("serial")
public class MapServlet extends BaseServlet {
	private static final String COMMAND = "c";
	private static final String AJAX = "a";
	private static final String PR_FILE_PATH = System.getProperty("user.dir") + "/WEB-INF/pr-blank.xlsx";
	private static final String VP_FILE_PATH = System.getProperty("user.dir") + "/WEB-INF/vp-blank.xlsx";
	private static final String SN_FILE_PATH = System.getProperty("user.dir") + "/WEB-INF/sn-blank.xlsx";
	private static final String PL_FILE_PATH = System.getProperty("user.dir") + "/WEB-INF/pl-blank.xlsx";
	private static final String TM_FILE_PATH = System.getProperty("user.dir") + "/WEB-INF/tm-blank.xlsx";
	private Logger log = Logger.getLogger(this.getClass().getName());
	
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(USER);
		String command = request.getParameter(COMMAND);
		String ajax_marker = request.getParameter(AJAX);
		String view = DEFAULT_VIEW;
		// clear messages
		session.setAttribute(MESSAGE, new Msg(Msg.TYPE_NORMAL, ""));
		if ("create".equalsIgnoreCase(command)) {
			view = doCreate(user, request, response);
		} else if ("delete".equalsIgnoreCase(command)) {
			view = doRemove(request, response);
		} else if ("logout".equalsIgnoreCase(command)) {
			view = doLogout(request);
			// } else if ("wizard".equalsIgnoreCase(command)) {
			// view = doWizard(request);
		} else if ("embed".equalsIgnoreCase(command)) {
			view = doEmbed(request);
		} else if ("sheet".equalsIgnoreCase(command)) {
			view = doSheet(request);
		}
		if(ajax_marker==null){
			request.getRequestDispatcher(view).include(request, response);
		}
	}
	
	private String doEmbed(HttpServletRequest request) {
		String view = DEFAULT_VIEW;
		String type = request.getParameter(P_TYPE);
		String key = request.getParameter(P_KEY);
		request.setAttribute(R_KEY, key);
		request.setAttribute(R_TYPE, type);
		view = EMBEDCODE_VIEW;
		return view;
	}
	
	private String doLogout(HttpServletRequest request) {
		request.getSession().invalidate();
		return DEFAULT_VIEW; 
	}

	private String doSheet(HttpServletRequest request)
			throws ServletException, IOException {
		String resourceId = request.getParameter(P_RESID);
		String docURL = "";
		try {
			String account = ((User) request.getSession().getAttribute(USER)).getEmail();
			DocumentListEntry doc = DLDAUtil.getDocByKey(getDocService(), resourceId);
			if (!DLDAUtil.isDocSharedTo(getDocService(), doc, account)) {
				DLDAUtil.shareDoc(getDocService(), doc, account);
				request.getSession().setAttribute(resourceId, "true");
			}
			docURL = doc.getHtmlLink().getHref();
			
		} catch (Exception e) {
			//error occured
			log.severe(e.getMessage());
		} finally {
			request.setAttribute("link", docURL);
			request.setAttribute("resid", resourceId);
		}
		return SHEET_VIEW;
	}
	
	private String doRemove(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String resourceId = request.getParameter(P_RESID);
		String ajax_marker = request.getParameter(AJAX); 
		Msg msg = null;
		try {
			DLDAUtil.delete(getDocService(), resourceId);
			msg = new Msg(Msg.TYPE_NORMAL, "Map deleted!");
			log.info(resourceId + " deleted.");
		} catch (ServiceException e) {
			log.severe("Deletion of " + resourceId + " failed.");
			msg = new Msg(Msg.TYPE_ERROR, "Map deletion failed.");
		}
		request.getSession().setAttribute(MESSAGE, msg);
		if(ajax_marker!=null) {
			response.setContentType("text/plain");
			response.getWriter().print("1");
		}
		return DEFAULT_VIEW;
	}
	
	private String doCreate(User user, HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String userid = "U" + user.getId();
		String title = request.getParameter(P_TITLE);
		String type = request.getParameter(P_TYPE);
		String view = DEFAULT_VIEW;
		String ajax_marker = request.getParameter(AJAX); 

		if (type != null) {
			Msg msg = null;
			try {
				DocumentListEntry doc = null;
				doc = DLDAUtil.uploadDoc(getTemplatePath(type), userid + DOT
						+ type + COLON + title);
				doc = DLDAUtil.saveDoc(getDocService(), doc);
				log.info("New " + type + " map created for "
						+ user.getUsername() + "");
				msg = new Msg(Msg.TYPE_NORMAL, "New map created!");
				if(ajax_marker!=null){
					Document docModel = new Document();
					docModel.setLink(doc.getHtmlLink().getHref());
					String id = docModel.getResourceId();
					id = id.substring(0, id.indexOf("&")); //aloyks
					response.setContentType("text/plain");
					response.getWriter().print(id);
				}
			} catch (Exception e) {
				log.severe("Error on create new map.");
				//e.printStackTrace();
			}
			msg = new Msg(Msg.TYPE_NORMAL, "New map created!");
			request.getSession().setAttribute(MESSAGE, msg);
		} else {
			view = CREATEMAP_VIEW;
		}
		return view;
	}
	
	private String getTemplatePath(String type) {
		String p = "";
		if ("PR".equalsIgnoreCase(type)) {
			p = PR_FILE_PATH;
		} else if ("VP".equalsIgnoreCase(type)) {
			p = VP_FILE_PATH;
		} else if ("SN".equalsIgnoreCase(type)) {
			p = SN_FILE_PATH;
		} else if ("PL".equalsIgnoreCase(type)) {
			p = PL_FILE_PATH;
		} else if ("TM".equalsIgnoreCase(type)) {
			p = TM_FILE_PATH;
		}
		return p;
	}
}
